<?php
namespace control;
/*
*派遣单位类
*/

class laborCompanyClass extends adIndexClass
{
    private const page = 'laborCompany'; # 权限
    private const table = 'labor_company'; # 数据表
    private const title = '派遣单位';
    private array $invoiceOption = ['普票','专票'];

    public function searchHtml(): string
    {
        return text(["name" => "code", "title" => "派遣单位编码"]) .
            text(["name" => "name", "title" => "派遣单位名称"]) .
            text(["name" => "contactName", "title" => "常用联系人"]) .
            text(["name" => "contactPhone", "title" => "常用联系电话"]) .
            text(["name" => "taxpayerID", "title" => "纳税人识别码"]);
    }

    /*列表页-查询条件*/
    public function home()
    {
        return $this->homeFun($this->search($this->searchHtml()));
    }

    public function homeSearch(): bool|string
    {
        $like = [
            "name" => $this->post('materialName'),
            "orderNo" => $this->post('code'),
            "contactName" => $this->post('contactName'),
            "contactTel" => $this->post('contactPhone'),
            "companyNum" => $this->post('taxpayerID'),
        ];
        //全等查询数组
        $equal = array(
        );
        //获取查询结果
        $where = search(["like" => $like, "=" => $equal]);
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "orderNo desc"));
        $_SESSION[self::page]['sql'] = $page['sql'];
        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        $tr[] = [$checkAll, '派遣单位编码', '派遣单位名称',  '常用联系人', '常用联系电话', '微信/QQ', '纳税人识别码', '状态'];
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
                'edit' => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
            );
            $tr[] = [$this->dominate($dominate), $array['orderNo'], $array['name'], $array['contactName'], $array['contactTel'], $array['wechat'] . '/' . $array['qq'], $array['companyNum'], $array['state']];
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "import")) {
            $button .=
                importTemplateClass::importTemplateButton(self::page).
                $this->upButton(array("title" => "导入", "fun" => "importData"));
        }
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'启用'})\" class='spanButton'>启用</span>\n";
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'停用'})\" class='spanButton'>停用</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */

    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data = [];
            $sql = $_SESSION[self::page]['sql'];
            $title = ['派遣单位编码', '派遣单位名称',  '常用联系人', '常用联系电话', '微信/QQ', '纳税人识别码', '状态'];
            $result = self::sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    $data[] = [$array['orderNo'], $array['name'],  $array['contactName'], $array['contactTel'], $array['wechat'] . '/' . $array['qq'], $array['companyNum'], $array['state']];
                }
            }
            $text = $this->control['name'] . "导出了派遣单位";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "派遣单位.xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        } else {
            $title = ['*派遣单位编码', '*派遣单位名称', '常用联系人', '常用联系电话', '微信',  'QQ', '通讯地址', '邮政编码','备注', '发票类型', '默认税率', '开户行', '银行账号', '注册地址', '纳税人识别号', '默认付款方式', '默认结算方式', '对账日(日期)'];
            $data[] = ['s001', '雨木科技',  '李同学', '18666666666', 'weixin', '12345680',  '重庆市南岸区通讯地址', '40123','测试备注', '专票', '1', '开户行', '银行账号', '注册地址', '91500108320394248N', '默认付款方式', '默认结算方式', '2021-01-01'];
            $text = $this->control['name'] . "下载了派遣单位导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, '派遣单位导入模板.xlsx');
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入分析*/

    public function importData()
    {
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        } else {
            $data = $this->importHead();
            $x = 0;
            $text = '';
            $taxOption =  para('taxRate','，');
            $payTypeOption = para('payType','，');
            $supplierSettlementOption = para('supplierSettlement','，');
            foreach ($data as $i => $row) {
                if ($i > 0) {
                    $cell = formSubArray($row);
                    $cell[17] = self::importDateFormat($cell[17]);
                    $field = [
                        'id' => self::getId(),
                        'stid' => self::$stid,
                        'state' => '启用',
                        'orderNo' => $cell[0],
                        'name' => $cell[1],
                        'contactName' => $cell[2],
                        'contactTel' => $cell[3],
                        'wechat' => $cell[4],
                        'qq' => $cell[5],
                        'addressMx' => $cell[6],
                        'postCode' => $cell[7],
                        'text' => $cell[8],
                        'invoiceType' => $cell[9]?:'普票',
                        'taxRate' => $cell[10],
                        'companyBank' => $cell[11],
                        'companyBankNum' => $cell[12],
                        'companyAddress' => $cell[13],
                        'companyNum' => $cell[14],
                        'payType' => $cell[15],
                        'settleType' => $cell[16],
                        'checkDay' => $cell[17],
                    ];
                    $annotation = [
                        'orderNo' => '派遣单位编码',
                        'name' => '派遣单位名称',
                    ];
                    $rules = [
                        'orderNo' => 'required',
                        'name' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();

                    if ($result === false) {
                        $text .= "第【{$i}】行：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                    } elseif (static::total(['table' => self::table, 'where' => " and orderNo = '$field[orderNo]'"]) > 0) {
                        $text .= "第【{$i}】行：已存在此编码的" . self::title."<br>";
                    }elseif(!empty($field['invoiceType']) && !in_array($field['invoiceType'],$this->invoiceOption)){
                        $text .= "第【{$i}】行：此发票类型不在可选范围中<br>";
                    }elseif(!empty($field['taxRate']) && !in_array($field['taxRate'],$taxOption)){
                        $text .= "第【{$i}】行：税率不在可选范围中<br>";
                    }elseif(!empty($field['payType']) && !in_array($field['payType'],$payTypeOption)){
                        $text .= "第【{$i}】行：此默认付款方式不在可选范围中<br>";
                    }elseif(!empty($field['settlement']) && !in_array($field['settlement'],$supplierSettlementOption)){
                        $text .= "第【{$i}】行：此默认结算方式不在可选范围中<br>";
                    }else {
                        $warn = static::insert(["table" => self::table, "field" => $field,]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= self::title . "【{$cell[1]}】导入成功<br>";
                        } else {
                            $text .= self::title . "【{$cell[1]}】导入失败：编辑失败<br>" . $warn;
                        }
                    }
                }
            }
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $warn = "成功导入" . $x . "条数据，详情请查看日志！";
            $_SESSION['warn'] = $warn;
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }


    /**
     * 启用/停用
     */
    public function stateSwitch(): bool|string
    {
        $type = $this->post('type');
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否修改所选数据状态为：" . $type,
            ),
        ), 'hidden' => hidden(array('name' => 'type', 'value' => $type)), 'formTwo' => 'listForm'));
        //返回
        return $this->layer(array("title" => "状态切换", "height" => 165, "width" => 500, "html" => $html));
    }

    /**
     * 启用/停用
     */
    public function stateSwitchEdit(): bool|string
    {
        $idArr = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        $state = $this->post('type');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif (!in_array($state, ['启用', '停用'])) {
            $json['warn'] = "类型错误";
        } else {
            $field = [
                'state' => $state,
            ];
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "')"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "的状态为【{$state}】， id：【" . implode("','", $idArr) . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }

    /*基本资料-弹出层*/
    public function edit(): string
    {
        $id = $this->get('id') ?: self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
	    $button[]  = [
		    "name"  => L('public.save'),
		    "type"  => "点击事件",
		    "cla"   => $this->get('cla'),
		    "fun"   => "subForm('" . self::page . "EditForm, laborCompanyImgSingleForm', root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
		    "post"  => ["id" => $this->get('id')],
		    'style' => 'li-btn-blue-bg',
	    ];
	    $button[]  = [
		    "name"  => L('public.saveDraft'),
		    "type"  => "点击事件",
		    "cla"   => $this->get('cla'),
		    "fun"   => "saveTemp('" . self::page . "', 'edit', '" . self::page . "EditForm')",
		    "post"  => ["id" => $this->get('id')],
		    'style' => 'li-btn-green-bg',
	    ];
        //表单
        $data['html'] = $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button),
                ],
                ["基本信息"],
                [
                    must . '派遣单位编码' => text(['name' => "code", 'class' => 'text', 'value' => $info['orderNo']]),
                    must . '派遣单位名称' => text(['name' => "name", 'class' => 'text', 'value' => $info['name']]),
                ],

                [
                    '常用联系人' => text(['name' => "contactName", 'class' => 'text', 'value' => $info['contactName']]),
                    '常用联系电话' => text(['name' => "contactPhone", 'class' => 'text', 'value' => $info['contactTel']]),
                ],
                [
                    '微信' => text(['name' => "wechat", 'class' => 'text', 'value' => $info['wechat']]),
                    'QQ' => text(['name' => "qq", 'class' => 'text', 'value' => $info['qq']]),
                ],
                [
                    '通讯地址' => text(['name' => "addressMx", 'class' => 'text', 'value' => $info['addressMx']]),
                    '邮政编码' => text(['name' => "postCode", 'class' => 'text', 'value' => $info['postCode']]),
                ],
                [
                    '备注' => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
                [
                    '财务信息'
                ],
                [
                    '发票类型' => radio(['name' => "invoiceType", 'class' => 'text', 'checked' => $info['invoiceType']?:$this->invoiceOption[0], 'value' => $this->invoiceOption]),
                    '默认税率' => select(['name' => "taxRate", 'class' => 'text', 'title' => '默认税率', 'value' => $info['taxRate'], 'option' => explode('，', para('taxRate'))]),
                ],
                [
                    '开户行' => text(['name' => "bankName", 'class' => 'text', 'value' => $info['companyBank']]),
                    '银行账号' => text(['name' => "bankAccount", 'class' => 'text', 'value' => $info['companyBankNum']]),
                ],
                [
                    '注册地址' => text(['name' => "registeredAddress", 'class' => 'text', 'value' => $info['companyAddress']]),
                    '纳税人识别号' => text(['name' => "taxpayerID", 'class' => 'text', 'value' => $info['companyNum']]),
                ],
                [
                    '默认付款方式' => select(['name' => "payment", 'title' => '默认付款方式', 'class' => 'text', 'value' => $info['payType'], 'option' => explode('，', para('payType'))]),
                    '默认结算方式' => radio(['name' => "settlement", 'title' => '默认结算方式', 'class' => 'text', 'checked' => $info['settleType'], 'option' => explode('，', para('supplierSettlement')),]),
                ],
                [
                    '对账日' => text(['name' => "checkDay", 'class' => 'text', 'value' => $info['checkDay'], 'laydate' => []]),
                ],
                ['资质证照'],
                [

                ]
            ],
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
            'button' => ' ',
        ]);
        $licenseUrl = query('file', "targetId = '$id' and target ='营业执照'");
        $photo = array(
            array("title" => "营业执照", 'type' => '营业执照', "url" => $licenseUrl['src'], 'id' => $id),
        );
        $data['html'] .= self::singlePhoto($photo);
        //返回
        return $this->tab($data);
    }


    /**
     * @param $data
     * @return string
     */
    public static function singlePhoto($data): string
    {
        $li = "";
        foreach ($data as $array) {
            //编辑表单
            $click = '';
            if (!empty($array['id'])) {
                $click = "<img  src='" . root . "img/images/clickEdit.png' onClick=\"clickUpload('{$array['type']}')\" class='clickIco'>";
            }
            //点击显示大图功能
            if (empty($array['url'])) {
                $img = "<img class='smallImg imgHover' data-type='{$array['type']}' src='" . root . "img/images/emptyImg.jpg'>";
            } else {
                if (strstr($array['url'], "http") !== false) {
                    $r = "";
                } else {
                    $r = root;
                }
                $img = "<a target='_blank' href='" . $r . $array['url'] . "' title='点击查看大图'><img data-type='{$array['type']}' class='smallImg imgHover' src='" . $r . $array['url'] . "'></a>";
            }
            //打印本图像框
            $li .= "
			<li>
				" . $click . "
				<p>" . $array['title'] . "</p>
				<div>" . $img . "</div>
			</li>
			";
        }
        $data['cla'] = $data['cla'] ?? self::page;
        return <<<efo
		
<form name="{$data['cla']}ImgSingleForm"><div class='imgSingle' style="margin: 10px">
			<ul>{$li}</ul>
			<div class='clear'></div>
		</div><div class='hidden'><input name="type" type="hidden" ><input name='imgFile' accept="image/*" id='imgFile' type='file' onchange="uploadImgFile('{$data['cla']}ImgSingleForm',root+'control/adIndex.html?cla={$data['cla']}&fun=uploadIco')"></div></form>
		<script>
		//点击上传图片
        function clickUpload(type){
            $('[name=type]').val(type);
            $('#imgFile').click();
        }
        //上传图片
        function uploadImgFile(formName,url){
            let form = $("form[name='"+formName+"']")[0];
            let id= $("[name='id']").val();
            let type = $("[name='type']").val();
            let formData = new FormData(form);
            formData.append('id',id);
            $.ajax({
                type: "POST",
                contentType: false,
                processData: false,
                url: url,
                data: formData,
                cache: false,
                success: function (res) {
                    let result = JSON.parse(res);
                    $("[name='imgFile']").val('');
                    if (result.warn === 2) {
                        $("[data-type='"+type+"']").attr('src',result.data.src);
                        $("[data-type='"+type+"']").nextAll().remove();
                        $("[data-type='"+type+"']").after(result.data.fileHtml)
                    }else{
                        warn(result.warn)
                    }
                },
                error: function (e) {
                    console.log(e)
                    warn("上传失败");
                }
            });
        }
        </script>
efo;
    }

    /**
     *上传图片
     */
    function uploadIco(): bool|string
    {
        $type = $this->post('type');
        $result = $this->saveFile($_FILES['imgFile'], 'laborCompany', explode(',', para('fileFormat')));
        $id = $this->post('id');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($type)) {
            $json['warn'] = '未找到类型';
        } elseif (empty($id)) {
            $json['warn'] = '未找到ID';
        } elseif (!$result['code']) {
            $json['warn'] = $result['warn'];
        } else {
            $field = array(
                'src' => $result['src'],
                'name' => $result['fileName'],
                'size' => $result['size'],
                'format' => $result['suffix'],
            );
            $file = query('file', "targetId = '$id' and target = '$type'");
            if (empty($file['id'])) {
                $field = array_merge($field, [
                    'id' => self::getId(),
                    'stid' => self::$stid,
                    'target' => $type,
                ]);
                $json['warn'] = static::insert(array(
                    'table' => 'file',
                    'field' => $field
                ));
                $fileId = $field['id'];
            } else {
                $json['warn'] = static::update(array(
                    'table' => 'file',
                    'field' => $field,
                    'where' => "id = '$file[id]'"
                ));
                $fileId = $file['id'];
            }
            //添加日志
            if (in_array($json['warn'], ['新增成功', '更新成功'])) {
                fileDelete($file['src']);//删除之前的图片
                $json['warn'] = 2;
                $json['data']['src'] = root . $result['src'];
                $json['data']['fileHtml'] = hidden(array('name' => "imgId[]", 'value' => $fileId));
            }
        }
        return json_encode($json, 320);
    }


    /*异步处理*/
    public function editEdit(): bool|string
    {
        $id = $this->post('id') ?: self::getId();
        $fileId = $this->post('imgId');
        $field = [
            'orderNo' => $this->post('code'),
            'name' => $this->post('name'),
            'contactName' => $this->post('contactName'),
            'contactTel' => $this->post('contactPhone'),
            'wechat' => $this->post('wechat'),
            'addressMx' => $this->post('addressMx'),
            'postCode' => $this->post('postCode'),
            'qq' => $this->post('qq'),
            'text' => $this->post('text'),
            'invoiceType' => $this->post('invoiceType'),
            'taxRate' => (float)$this->post('taxRate')/100,
            'companyBank' => $this->post('bankName'),
            'companyBankNum' => $this->post('bankAccount'),
            'companyAddress' => $this->post('registeredAddress'),
            'companyNum' => $this->post('taxpayerID'),
            'payType' => $this->post('payment'),
            'settleType' => $this->post('settlement'),
            'checkDay' => $this->post('checkDay'),
        ];
        $annotation = [
            'orderNo' => '派遣单位编码',
            'name' => '派遣单位名称',
        ];
        $rules = [
            'orderNo' => 'required',
            'name' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(['table' => self::table, 'where' => " orderNo = '$field[orderNo]' and id !='$id'"]) > 0) {
            $json['warn'] = "已存在此编码的" . self::title;
        } elseif (empty($info['id'])) {
            $field = array_merge($field, ["id" => $id, 'stid' => self::$stid, 'state' => '启用']);
            $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
        } else {
            $json['warn'] = static::update(["table" => self::table, "field" => $field, "where" => "id = '" . $id . "'"]);
        }

        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //更新文件
            if (is_array($fileId) && !static::isNull($fileId)) {
                update(['table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileId) . "')"]);
            }
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个" . self::title . "：" . $field['name'] . ",ID：" . $id;
            $this->logText(["type" => self::page, "text" => $text]);
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            if ($this->get('source') == 'home') {
                $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=home';
            } else {
                $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=detail&id=' . $id;
            }
        }
        //返回
        resp:
        return json_encode($json, 320);
    }

    /**
     * 明细
     * @return bool|string
     */
    public function detail(): bool|string
    {
        $info = query(self::table, " id = '" . $this->get('id') . "' ");
        if (!$this->power(self::page, "see")) {
            $html = "你没有查看派遣单位的权限";
        } elseif (empty($info['id'])) {
            $html = "未找到此派遣单位";
        } else {
            $data = [
                "id" => $info['id'],
                'menu' => [
                    "detail" => "基本信息",
                    'contact' => '联系人',
                    'file' => ['cla' => 'file', 'fun' => 'laborCompanyFile', 'name' => '附件'],
                ]
            ];
            //按钮
            $button = [];
            if ($this->power(self::page, "edit")) {
                $button[] = [
                    "name" => "编辑",
                    "type" => "顶部页卡",
                    'title' => '编辑',
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . "&fun=edit&id=" . $info['id'],
                    'style' => 'li-btn-blue-bg',
                ];
                $state = $info['state'] == '停用' ? '启用' : '停用';
                $button[] = [
                    "name" => $state,
                    "type" => "点击事件",
                    'title' => '修改状态',
                    "fun" => "layer('" . $this->get('cla') . "','stateSwitch',{id:'" . $info['id'] . "',type:'{$state}'})",
                ];

            }
            if ($this->power(self::page, 'del')) {
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "delete",
                    "post" => ["id" => $info['id']],
                ];
            }

            $licenseUrl = query('file', "targetId = '$info[id]' and target ='营业执照'");
            $photo = array(
                array("title" => "营业执照", 'type' => '营业执照', "url" => $licenseUrl['src']),
            );
            //生成表单
            $data['html'] = $this->tableShow([
                "button" => $button,
                [
                    [
                        "派遣单位编码" => $info['orderNo'],
                        "派遣单位名称" => $info['name'],
                    ],
                    [
                        "常用联系人" => $info['contactName'],
                        "常用联系电话" => $info['contactTel'],
                        "微信" => $info['wechat'],
                    ],
                    [
                        "QQ" => $info['qq'],
                        "通讯地址" => $info['addressMx'],
                        "邮政编码" => $info['postCode'],
                    ],
                    [
                        "备注" => $info['text'],
                    ],
                ],
                "财务信息" => [
                    [
                        "发票类型" => $info['invoiceType'],
                        "默认税率" => ($info['taxRate']*100) . '%',
                        "开户行" => $info['companyBank'],
                    ],
                    [
                        "银行账号" => $info['companyBankNum'],
                        "注册地址" => $info['companyAddress'],
                        "纳税人识别号" => $info['companyNum'],
                    ],
                    [
                        "默认付款方式" => $info['payType'],
                        "默认结算方式" => $info['settleType'],
                        "对账日" => $info['checkDay'],
                    ],
                ],
                "系统信息" => [
                    [
                        "创建人" => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                        "更新时间" => $info['updateTime'],
                    ],
                    [
                        "状态" => $info['state'],
                    ],
                ],
                "资质证照" => [
                    [
                        self::singlePhoto($photo)
                    ]
                ]
            ]);
            $html = $this->tab($data);
        }

        //返回
        return $html;
    }

    // 操作中转
    public function operate(): bool|string
    {
        $act = $this->post('act') ?? '';
        $pwd = $append = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            case 'delContact':
                $act = 'staffDel';
                $msg = '删除联系人';
                $title = self::page . 'Contact';
                $function = 'deleteContact';
                $append = [hidden(['name' => 'orderId', 'value' => $this->post['orderId']])];
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'append' => $append,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete(): bool|string
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '停用') {
                    $warn = "不是停用状态，暂不能删除";
                } else {
                    $result = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                    foreach ($result['array'] as $file) {
                        fileDelete($file['src']);
                    }
                    //删除附件
                    delete(array("table" => "file", "where" => " targetId = '$id' "));
                    delete(array("table" => "contacts", "where" => " orderId = '$id' "));
                    delete(array("table" => 'record', "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }


    // 'contact'         => '联系人',
    // 'attachment'      => '附件',
    // 'supply'          => '供货清单',
    // 'contracts'       => '合同',
    // 'purchaseOrder'   => '采购订单',
    // 'purchaseReceipt' => '采购收货',
    // 'purchaseReturn'  => '采购退货',
    // 'tickets'         => '收票记录',
    // 'follow'          => '跟进记录',

    /**
     * 派遣单位联系人
     */
    public function contact(): bool|string
    {
        $html =
            text(["name" => "name", "title" => "姓名"]) .
            text(["name" => "tel", "title" => "手机号"]) .
            text(["name" => "text", "title" => "备注"]) .
            hidden(array('name' => 'id', 'value' => $this->get('id')));
        $json['html'] = $this->search($html);
        return json_encode($json, 320);
    }

    /**
     * 操作记录
     * @return bool|string
     */
    public function contactSearch(): bool|string
    {
        $id = $this->post('id');
        //查询结果
        $where = " orderId = '$id' AND type='派遣单位' ";
        $equal = [
            'name' => $this->post('name'),
            'tel' => $this->post('tel'),
            'text' => $this->post('text'),
        ];
        $like = [
            'name' => $this->post('name'),
            'tel' => $this->post('tel'),
            'text' => $this->post('text'),
        ];
        //生成查询语句
        $where .= search([
            "=" => $equal,
            "like" => $like,
        ]);
        $page = $this->page([
            "table" => 'contacts',
            "where" => $where,
            "order" => "`time` desc",
        ]);
        //获取表头
        $checkAll = $this->checkAll("listForm", "id");
        $tr[] = [$checkAll, '姓名', '性别', '职务', '手机号', '微信/QQ', '地址', '备注', '更新时间'];
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail";
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = [
                "box" => [
                    "name" => "id",
                    "value" => $array['id']
                ],
                'edit' => ["title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=editContact&id=" . $array['id'] . "')"],
            ];
            $tr[] = [$this->dominate($dominate), $array['name'], $array['gender'], $array['position'], $array['tel'], $array['wechat'] . '/' . $array['qq'], $array['address'], $array['text'], $array['updateTime']];
        }
        //控件
        $button = '';
        if ($this->power(self::page, "staffEdit")) {
            $button .= "<span class='spanButton' onclick=\"newIframe('新建联系人', '" . $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editContact&id=' . suiji() . "&orderId=$id')\">新增</span>\n";
        }
        if ($this->power(self::page, "staffDel")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {act: 'delContact', orderId: '$id'})\">删除</span>\n";
        }
        //控件
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    public function editContact()
    {
        $info = query('contacts', " id = '" . $this->get('id') . "' ");
        //表单
        $data['html'] = $this->layerEdit([
            "table" => [
                [
                    must . '姓名' => text(['name' => "name", 'class' => 'text', 'value' => $info['name']]),
                ],
                [
                    must . '性别' => radio(['name' => "gender", 'value' => ['男', '女', '未知'], 'checked' => $info['gender']]),
                ],
                [
                    must . '职位' => text(['name' => "position", 'class' => 'text', 'value' => $info['position']]),
                ],
                [
                    must . '手机号' => text(['name' => "tel", 'class' => 'text', 'value' => $info['tel']]),
                ],
                [
                    '微信' => text(['name' => "wechat", 'class' => 'text', 'value' => $info['wechat']]),
                ],
                [
                    'QQ' => text(['name' => "qq", 'class' => 'text', 'value' => $info['qq']]),
                ],
                [
                    '地址' => text(['name' => "address", 'class' => 'text', 'value' => $info['address']]),
                ],
                [
                    "备注：" => textarea(["name" => "text", "value" => $info['text']])
                        . hidden(['name' => 'id', 'value' => $info['id'] ? $info['id'] : $this->get('id')]) . hidden(['name' => 'orderId', 'value' => $info['orderId'] ?: $this->get('orderId')]),
                ],
            ],
            'button' => '<button class="button left-bottom" onclick="subForm(\'' . $this->get('cla') . 'EditContactForm\',root+\'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editContactEdit\')">保存</button>',
        ]);
        $html = '';
        //返回
        return $this->tab($data) . $html;
    }

    /*成本表基本资料新增或修改-异步处理*/
    public function editContactEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'orderId' => $this->post('orderId'),
            'name' => $this->post('name'),
            'gender' => $this->post('gender'),
            'position' => $this->post('position'),
            'tel' => $this->post('tel'),
            'wechat' => $this->post('wechat'),
            'qq' => $this->post('qq'),
            'address' => $this->post('address'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'orderId' => '派遣单位id',
            'name' => '姓名',
            'gender' => '性别',
            'position' => '职位',
            'tel' => '手机号',
            'wechat' => '微信',
            'qq' => 'QQ',
            'address' => '地址',
            'text' => '备注',
        ];
        $rules = [
            'orderId' => 'required',
            'name' => 'required',
            'gender' => 'required',
            'position' => 'required',
            'tel' => 'required|tel',
            // 'wechat'      => 'required',
            // 'qq'          => 'required|unsigned_int',
            // 'text'        => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "staffDel")) {
            $json['warn'] = "你没有编辑联系人的权限";
        } else {
            $table = 'contacts';
            $where = " id = '$id' AND orderId = '$field[orderId]' ";
            $info = query($table, $where);
            if (sqlNum($table, " (name = '{$field['name']}' AND tel = '{$field['tel']}') AND id <> '$id'   ") > 0) {
                $json['warn'] = "联系人「{$field['name']}」手机号 「{$field['tel']}」重复";
                goto resp;
            }
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'type' => '派遣单位',
                    'stid' => $this->control['stid'],
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => $table, "field" => $field,]);
            } else {
                $json['warn'] = static::update([
                    "table" => $table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&menu=contact&id=" . $this->post('orderId');
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function deleteContact(): bool|string
    {
        $array = $this->post('listId') ?? $this->post('id');
        $orderId = $this->post('orderId');
        if (!$this->power(self::page, "staffDel")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } elseif (empty($orderId)) {
            $json['warn'] = "参数错误";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $where = " id = '$id' AND orderId = '$orderId' ";
                $info = query("contacts", $where);
                if (!static::isNull($info['id'])) {
                    delete(["table" => "contacts", "where" => $where]);
                    //返回
                    $warn = "删除成功";
                    $x++;
                    $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
                }
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "联系人，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "联系人，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&menu=contact&id=" . $this->post('orderId');
        }
        return json_encode($json, 320);
    }


    /**
     * 生成派遣单位或客户流水
     * @param string $typeId 对象ID (客户ID/派遣单位ID)
     * @param string $classify 类别（销售退货/销售发货/采购退货/采购收货）
     * @param float $money 金额
     * @param string $targetDate 单据日期（销售发货单等的日期）
     * @param string $orderNo 单据编号(销售发货单等的编号)
     * @param string $text 备注 （"出库单【1221202211】"）
     * @param null $hiddenText 隐藏备注 （出库单ID:211212213）
     * @return bool|string
     */
    public static function insertRecord(string $typeId, string $classify, float $money, $sourceTable, $sourceId, $targetDate, $orderNo, $text, $hiddenText = null): bool|string
    {

        switch ($classify) {
            case '销售退货':
                $bool = self::record_cl($typeId, '+', -$money, $targetDate, $sourceTable, $sourceId, $text, '客户', $orderNo, $hiddenText, classify: $classify);
                break;
            case '销售发货':
                $bool = self::record_cl($typeId, '+', $money, $targetDate, $sourceTable, $sourceId, $text, '客户', $orderNo, $hiddenText, classify: $classify);
                break;
            case '采购退货':
                $bool = self::record_cl($typeId, '-', $money, $targetDate, $sourceTable, $sourceId, $text, '派遣单位', $orderNo, $hiddenText, classify: $classify);
                break;
            case '采购收货':
                $bool = self::record_cl($typeId, '-', -$money, $targetDate, $sourceTable, $sourceId, $text, '派遣单位', $orderNo, $hiddenText, classify: $classify);
                break;
            default:
                $bool = true;
                break;
        }
        return $bool;
    }

    /**
     * 记录派遣单位和客户的账户流水
     * @param string $typeId 对象ID
     * @param string $direction +/-
     * @param float $money 变动金额
     * @param $targetDate
     * @param string $text 备注
     * @param string $type 类型
     * @param string $orderNo 单据编号
     * @param null $hiddenText
     * @param string $classify
     * @return bool|string
     */
    public static function record_cl(string $typeId, string $direction, float $money, $targetDate, $sourceTable, $sourceId, string $text = '', string $type = '客户', $orderNo = '', $hiddenText = null, string $classify = ''): bool|string
    {
        //为正是其他人要给平台的钱，负则是平台要给其他人钱
        if (empty($typeId)) {
            return '未找到记录账户';
        } elseif (empty($direction) || !in_array($direction, ['+', '-'])) {
            return '未找到收入支出类型';
        } elseif (empty($type) || !in_array($type, ['客户', '派遣单位'])) {
            return '未找到账户类型';
        } elseif (empty($money) || preg_match(checkPrice, abs($money)) == 0) {
            return '未找到变动金额或金额格式错误';
        } elseif (empty($targetDate)) {
            return '未找到日期';
        } else {
            if (!in_array($classify, ['核销', '收款单核销', '付款单核销'])) {
                $order = query($sourceTable, "id = '$sourceId'");
                $material = query('material', "id = '$order[materialId]'");
                $materialSku = query('material_sku', "id = '$order[materialSkuId]'");
            }
            $warn = static::insert(array(
                'table' => 'record',
                'field' => array(
                    'coid' => self::$coid,
                    'typeId' => $typeId,
                    'type' => $type,
                    'direction' => $direction,
                    'money' => $money,
                    'classify' => $classify,
                    'balance' => self::money($typeId) + $money,
                    'text' => $text,
                    'orderNo' => $orderNo,
                    'sourceTable' => $sourceTable,
                    'sourceId' => $sourceId,
                    'materialId' => $material['id'] ?? '',
                    'materialSkuId' => $materialSku['id'] ?? '',
                    'num' => $order['num'] ?? 0,
                    'price' => $order['price'] ?? 0,
                    'unit' => $order['unit'] ?? '',
                    'targetDate' => $targetDate,
                    'stName' => self::$user['name'],
                    'hiddenText' => $hiddenText,
                )
            ));
            if ($warn != '新增成功') {
                return '流水新增失败';
            }
        }
        return true;
    }

    /**
     * 账户余额
     * @param float $typeId
     * @return mixed
     */
    public static function money($typeId): mixed
    {
        return find(array('table' => "record", 'where' => "typeId = '$typeId'", 'sum' => "money"));
    }
}
